#!/usr/bin/env python
"""Contains useful utility functions.
"""
__author__ = 'Don B. Stringham'
__version__ = '0.01'
__date__ = '10-27-2006 12:46 PM'
#-IMPORTS----------------------------------------------------------------------
import os
import re
import sys
import socket
import struct
#-CONSTANTS--------------------------------------------------------------------
str_dict = dict(sep=os.sep,
                home=os.getenv('HOME')) #Will be None if env. var. isn't there.
#-FUNCTIONS--------------------------------------------------------------------
def convert_str(template, opener='[', closer=']'):
    """Allows for easier string replacements.  IE. "My home dir is [home]"
    [home] is replaced with /home/stringhamdb in the string.
    """
    opener = re.escape(opener)
    closer = re.escape(closer)
    pattern = re.compile(opener + '([_A-Za-z][_A-Za-z0-9]*)' + closer)
    return re.sub(pattern, r'%(\1)s', template.replace('%', '%%'))

#IP address manipulation functions, dressed up a bit."""
def dottedQuadToNum(ip):
    """Convert decimal dotted quad string to long integer
    """
    return struct.unpack('L',socket.inet_aton(ip))[0]

def numToDottedQuad(n):
    """Convert long int to dotted quad string
    """
    return socket.inet_ntoa(struct.pack('L',n))

def makeMask(n):
    """Return a mask of n bits as a long integer
    """
    return (2L<<n-1)-1

def ipToNetAndHost(ip, maskbits):
    """returns tuple (network, host) dotted-quad addresses given IP and mask
    size. (by Greg Jorgensen)
    """
    n = dottedQuadToNum(ip)
    m = makeMask(maskbits)
    host = n & m
    net = n - host
    return numToDottedQuad(net), numToDottedQuad(host)
